package controller.UserController;

import bean.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import common.AppVariable;
import common.ResultAjax;
import services.UserService;
import services.impl.UserServiceImpl;
import util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @auther hewenhui
 * @see <a href="hetp://www.codingmaster.com> java </a>
 */
@WebServlet("/change")
public class ChangeServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("text/json; charset=utf-8");

        // 是否登录
        HttpSession session = req.getSession(false);
        if (session == null) {
            String respJson = objectMapper.writeValueAsString(ResultAjax.fail(-1,"未登录，请先登录！"));
            resp.getWriter().write(respJson);
            return ;
        }
        // 获取参数
        String oldPassword = req.getParameter("oldPassword");
        String newPassword = req.getParameter("newPassword");
        String confirmPassword = req.getParameter("confirmPassword");


        System.out.println(oldPassword);
        System.out.println(newPassword);
        System.out.println(confirmPassword);




        // 判断参数

        if(StringUtil.isEmpty(oldPassword)
            ||StringUtil.isEmpty(newPassword)
            ||StringUtil.isEmpty(confirmPassword)
            ||!newPassword.equals(confirmPassword)){
            String respJson = objectMapper.writeValueAsString(ResultAjax.fail(-1,"参数有误！"));
            resp.getWriter().write(respJson);
            return ;
        }
        // 调用services层修改密码
        User user = (User) session.getAttribute(AppVariable.SESSION_USERINFO_KEY);
        if(user==null){
            String respJson = objectMapper.writeValueAsString(ResultAjax.fail(-1,"用户不存在，请重新登录！"));
            resp.getWriter().write(respJson);
            return ;
        }
        System.out.println("user"+user.toString());
        int ret = userService.changePassword(user.getUid(), newPassword);

        if (ret==1){
            String respJson = objectMapper.writeValueAsString(ResultAjax.succeed(null));
            resp.getWriter().write(respJson);
            return ;
        }
        String respJson = objectMapper.writeValueAsString(ResultAjax.fail(-1,"修改失败"));
        resp.getWriter().write(respJson);

    }
}
